import path from "path";

import { app, BrowserWindow, ipcMain } from "electron";

import { config } from "dotenv";
import Selenium from "./selenium/main";
config({ path: path.resolve(__dirname, "../.env." + process.env.NODE_ENV) });

const createWindow = async () => {
  const radio = 16 / 9;
  const windowWidth = 800;
  const mainWindow = new BrowserWindow({
    width: windowWidth + 14,
    height: windowWidth / radio + 56,
    title: "autoTest",
    webPreferences: {
      preload: path.join(__dirname, "./preload.js"),
      backgroundThrottling: false,
      contextIsolation: true,
      nodeIntegration: true,
      nodeIntegrationInWorker: true,
      webSecurity: true,
    },
  });

  Selenium({
    handle: (key: string, callback: any) => ipcMain.handle(key, callback),
    send: (key: string, ...args: Array<any>) =>
      mainWindow.webContents.send(key, ...args),
  });

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // 开发环境下，访问dev server的地址
    await mainWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
  } else {
    // 生产环境下，使用`file://`协议加载main.html
    let filePath = `./dist/index.html`;
    if (app.isPackaged) {
      if (process.platform === "win32") {
        // Windows 平台上的默认位置
        filePath = path.join(app.getAppPath(), filePath);
      } else if (
        process.platform === "darwin" ||
        process.platform === "linux"
      ) {
        // macOS 或 Linux 平台上的默认位置
        filePath = path.join(app.getPath("userData"), filePath);
      }
      mainWindow.loadFile(filePath);
    } else {
      mainWindow.loadURL(`app://${filePath}`);
    }
  }
  mainWindow.webContents.openDevTools();
};

app.isReady() ? createWindow() : app.on("ready", createWindow);

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("browser-window-created", () => {
  console.log("window-created");
});
